package com.fgba.express.security;

import com.fgba.express.util.BeanContextUtil;
import com.fgba.express.util.WeChatUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信openid登陆验证的过滤器
 *
 * @author fgba
 */
public class WeChatAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    private String codeParameter = "code";

    public WeChatAuthenticationFilter() {
        super("/weChatLogin");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException {

        String code = obtain(request, this.codeParameter);
        if (code == null || code.length() == 0) {
            throw new BadCredentialsException("code 为空.");
        }

        String openId = BeanContextUtil.getBean(WeChatUtil.class).getOpenId(code);

        WeChatAuthenticationToken authRequest = new WeChatAuthenticationToken(openId);

        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));

        return this.getAuthenticationManager().authenticate(authRequest);

    }

    protected String obtain(HttpServletRequest request, String parameter) {
        String value = request.getParameter(parameter);
        return value == null ? "" : value.trim();
    }

}
